package org.dei.dataserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import org.dei.perla.parser.expressions.Constant;
import org.dei.perla.parser.expressions.ConstantID;
import org.dei.perla.parser.grammar.ParseException;
import org.dei.perla.parser.grammar.Parser;
import org.dei.perla.parser.statements.Query;
import org.dei.perla.parser.util.PairValue;
import org.dei.perla.rockfall.gui.MainWindow;
import org.dei.perla.rockfall.utils.DatabaseDump;
import org.dei.perla.sys.device.fpc.dspic.DSPicFPC;
import org.dei.perla.sys.llqruntime.QueryAnalyzer;
import org.dei.perla.utils.PerlaRuntime;

public class DSPicMain {

	private static ArrayList<DSPicFPC> pDSPicFPCList;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final String tQueryDirectory = "test" + File.separatorChar + "query" + File.separatorChar + "query1.txt";
		FileInputStream tInputStream = null;
		Query tQuery = null;
		QueryAnalyzer tQA;
		pDSPicFPCList = new ArrayList<DSPicFPC>();
		ArrayList<PairValue<String, ? extends Constant>> pAttributeToSetList = new ArrayList<PairValue<String, ? extends Constant>>();
		
		try {
			tInputStream = new FileInputStream(tQueryDirectory);
		} 
		catch (FileNotFoundException e) {
		
			System.out.println("File not found!");
		}
	
		new Parser(tInputStream);
	
		try {
			
			tQuery = Parser.StatementSequence().get(0);
			
		} catch (ParseException e) {
			
			e.printStackTrace();
		}
		
		Server s = new Server(5606);
		s.start();
		tQA = new QueryAnalyzer(tQuery);
		
		for (ConstantID tID : tQA.getDeviceToSetID()){
			DSPicFPC tTempFpc = new DSPicFPC(s.getFpcPipes(tID.getValueInt()), tID.getValueInt());
			pDSPicFPCList.add(tTempFpc);
			Thread dbDump = new Thread(new DatabaseDump(tTempFpc.registerQuery(null)));
			dbDump.start();
		}
		
		// Creazione interfaccia grafica
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				MainWindow window = new MainWindow(null);
				window.showGui();
				
				// Aggiungo tutti i DSPic da cui voglio ricevere i dati
				for (DSPicFPC d : pDSPicFPCList) {
					window.addDevice("DSPic", d.registerQuery(null));
				}
			}
		});
		
		for (String tAttributeToSet : tQA.getAttributeToSet().keySet()){
			pAttributeToSetList.add(new PairValue<String, Constant>(tAttributeToSet,tQA.getAttributeToSet().get(tAttributeToSet)));
		}

		for (DSPicFPC tDSPicFPC : pDSPicFPCList) {
			tDSPicFPC.setUpdateAttributes(pAttributeToSetList);
		}
	}
}
